package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;


@Service
@Transactional
@Slf4j
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 生成页面上传到minio
     * @param articleId
     */
    @Override
    public void createHtmlToMinIO(Long articleId) {
        try {
            //1.查询文章的内容 ap_article_content,根据文章id查询 1400354435804303361
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, articleId));

            if(null != apArticleContent && StringUtils.isNotBlank(apArticleContent.getContent())){
                //2.通过freemarker生成一个html文件
                Template template = configuration.getTemplate("article.ftl");
                //合成
                Map<String,Object> dataModel = new HashMap<>();
                //模型数据
                dataModel.put("content", JSONArray.parse(apArticleContent.getContent()));
                //输出流，暂存数据
                StringWriter out = new StringWriter();

                template.process(dataModel,out);

                InputStream inputStream = new ByteArrayInputStream(out.toString().getBytes());

                //3.把文件上传到minio中
                String url = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId() + ".html", inputStream);

                //4.修改ap_article表中的static_url字段
                ApArticle apArticle = apArticleMapper.selectById(apArticleContent.getArticleId());
                apArticle.setStaticUrl(url);
                apArticleMapper.updateById(apArticle);
            }
        } catch (Exception e) {
            throw new RuntimeException("ArticleFreemarkerServiceImpl-生成文章详情页面|上传minio--失败");
        }
    }
}
